<?php
/**
 * This file is part from Ewuroweb Shop
 *
 * @package EW
 * @subpackage Core
 * 
 * @author Ivan I. Atanasov <i.atanasov@viscomp.bg>
 */

abstract class EW_Core_Form extends Zend_Form {

    /**
     * 
     * @var EW_Core_Controller
     * @access protected
     */
    protected $_controller = NULL;
    
    /**
     * 
     * @var unknown_type
     * @access protected
     */
    protected $_dbObject = NULL;
    
    /**
     * Default Constructor
     * 
     * @param array $options
     * @param EW_Core_Controller $controller
     * @param $dbObject
     * @return EW_Core_Form
     */
    public function __construct($options, &$controller, &$dbObject) {
        $this->_controller = $controller;
        $this->_dbObject = $dbObject;
        parent::__construct($options);
    }
    
    protected function _beforeSave() {}
    
    /**
     * Build the new record & save
     * 
     * @return void
     */
    protected function _save() {
        $formValues = $this->getValues();
        $dbAttributes = $this->_dbObject->getAttributes();
        try {
            
            foreach($formValues as $k=>$v) {
                if(array_key_exists($k, $dbAttributes)) {
                    $dbAttributes[$k] =$v;
                }
            }
            
            $this->_dbObject->setAttributes($dbAttributes);
            $this->_beforeSave();
            $this->_dbObject->save();
        }
        catch(Exception $e) {
            throw $e;
        }
        
        return $this->_controller->redirectTo('index');
    }
    
    /**
     * Initialize Form
     * 
     * @return unknown_type
     */
    abstract protected function _initialize();
    
    /**
     * Final Zend_Form::init()  overriding
     * 
     * @return void
     */
    final function init() {
        $this->_initialize();
        
        $request = $this->_controller->getRequest();
        if ( $request->isPost() ) {
            if ( $this->isValid($request->getPost())) {
                $this->_save();
                
            }
        }
    }
}
